from machine import Pin, Timer
import time
import network
import socket

# 全局状态变量
robot_state = {
    "gait": "triangle",  # 步态模式: wave/triangle
    "light": False,      # 补光灯状态
    "command": "stop",   # 运动指令: up/down/left/right/stop
    "uptime": 0          # 运行时间(秒)
}

# 初始化硬件
def init_hardware():
    # 补光灯控制引脚(示例)
    global light_pin
    light_pin = Pin(4, Pin.OUT, value=0)  # 默认关闭
    
    # LED状态指示灯
    global status_led
    status_led = Pin(5, Pin.OUT, value=0)  # 低电平灭
    
    # 初始化定时器(用于计算运行时间)
    timer = Timer(0)
    timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t: update_uptime())

def update_uptime():
    """更新运行时间"""
    robot_state["uptime"] += 1

# WiFi连接
def connect_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print(f"连接WiFi: {ssid}")
        wlan.connect(ssid, password)
        
        # 等待连接(带超时)
        timeout = 15
        while timeout > 0 and not wlan.isconnected():
            status_led.value(1)  # 闪烁指示连接中
            time.sleep(0.5)
            status_led.value(0)
            time.sleep(0.5)
            timeout -= 1
            print(f"等待连接...剩余{timeout}秒")
        
        if not wlan.isconnected():
            print("WiFi连接失败")
            return None
    
    print("WiFi连接成功")
    print(f"IP地址: {wlan.ifconfig()[0]}")
    status_led.value(1)  # 常亮表示连接成功
    return wlan

# 生成简化HTML(仅保留结构示意)
def get_simplified_html():
    html = """
    
    
    
    """.format(
        command=robot_state["command"],
        gait=robot_state["gait"],
        light="开" if robot_state["light"] else "关",
        uptime=robot_state["uptime"]
    )
    return html

# 解析客户端请求
def parse_request(request):
    request_str = str(request, 'utf-8')
    # 提取运动指令
    if "?cmd=up" in request_str:
        robot_state["command"] = "up"
    elif "?cmd=down" in request_str:
        robot_state["command"] = "down"
    elif "?cmd=left" in request_str:
        robot_state["command"] = "left"
    elif "?cmd=right" in request_str:
        robot_state["command"] = "right"
    elif "?cmd=stop" in request_str:
        robot_state["command"] = "stop"
    
    # 提取步态指令
    if "?gait=wave" in request_str:
        robot_state["gait"] = "wave"
    elif "?gait=triangle" in request_str:
        robot_state["gait"] = "triangle"
    
    # 提取灯光指令
    if "?light=toggle" in request_str:
        robot_state["light"] = not robot_state["light"]
        light_pin.value(1 if robot_state["light"] else 0)  # 控制硬件

# 启动Web服务器
def start_web_server(ip):
    addr = socket.getaddrinfo(ip, 80)[0][-1]
    server_sock = socket.socket()
    server_sock.bind(addr)
    server_sock.listen(1)
    print(f"Web服务器启动: http://{ip}")
    
    try:
        while True:
            client_sock, client_addr = server_sock.accept()
            try:
                # 接收请求
                request = client_sock.recv(1024)
                # 解析请求并更新状态
                parse_request(request)
                # 发送响应
                client_sock.send('HTTP/1.1 200 OK\r\n')
                client_sock.send('Content-Type: text/html\r\n')
                client_sock.send('Connection: close\r\n\r\n')
                client_sock.send(get_simplified_html())
            except Exception as e:
                print(f"处理请求错误: {e}")
            finally:
                client_sock.close()
    except Exception as e:
        print(f"服务器错误: {e}")
    finally:
        server_sock.close()

# 主函数
def main():
    # 配置参数
    WIFI_SSID = "LAPTOP-D3RPTUAA 6358"
    WIFI_PWD = "19234949992.ch"
    
    # 初始化
    init_hardware()
    
    # 连接WiFi
    wlan = connect_wifi(WIFI_SSID, WIFI_PWD)
    if not wlan:
        status_led.value(1)  # 连接失败常亮报警
        return
    
    # 启动服务器
    start_web_server(wlan.ifconfig()[0])

if __name__ == "__main__":
    main()